<script setup lang="ts">
import { getProfileAPI, putMemberProfileAPI, updateAvatarAPI } from '@/apis/profile'
import { useMemberStore } from '@/stores'
import type { Gender, ProfileResult } from '@/types/profile'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { provinceData } from '@/utils/province'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 获取个人信息
const profile = ref<ProfileResult>({} as ProfileResult)

// H5端地区选择相关数据
const provinces = ref(provinceData)
const selectedProvince = ref('')
const selectedCity = ref('')
const selectedArea = ref('')
const cities = ref<any[]>([])
const areas = ref<any[]>([])

// H5端地区选择处理函数
const onProvinceChange = (e: any) => {
  const province = provinces.value[e.detail.value]
  selectedProvince.value = province.name
  cities.value = province.children || []
  selectedCity.value = ''
  selectedArea.value = ''
  areas.value = []
  fullLocationCode[0] = province.code
  updateFullLocation()
}

const onCityChange = (e: any) => {
  const city = cities.value[e.detail.value]
  selectedCity.value = city.name
  areas.value = city.children || []
  selectedArea.value = ''
  fullLocationCode[1] = city.code
  updateFullLocation()
}

const onAreaChange = (e: any) => {
  const area = areas.value[e.detail.value]
  selectedArea.value = area.name
  fullLocationCode[2] = area.code
  updateFullLocation()
}

const updateFullLocation = () => {
  profile.value.fullLocation = [selectedProvince.value, selectedCity.value, selectedArea.value]
    .filter(Boolean)
    .join(' ')
}

const getProfile = async () => {
  const res = await getProfileAPI()
  console.log(res)
  profile.value = res.result

  // 如果有地区信息，初始化H5端选择器的状态
  if (profile.value.fullLocation) {
    const locations = profile.value.fullLocation.split(' ')
    // 找到对应的省份
    const province = provinces.value.find((p) => p.name === locations[0])
    if (province) {
      selectedProvince.value = province.name
      fullLocationCode[0] = province.code
      cities.value = province.children || []

      // 找到对应的城市
      const city = province.children?.find((c) => c.name === locations[1])
      if (city) {
        selectedCity.value = city.name
        fullLocationCode[1] = city.code
        areas.value = city.children || []

        // 找到对应的区县
        const area = city.children?.find((a) => a.name === locations[2])
        if (area) {
          selectedArea.value = area.name
          fullLocationCode[2] = area.code
        }
      }
    }
  }
}
onLoad(() => {
  getProfile()
})

/**
 * todo: 修改头像
 */
// 修改头像
const onChangeAvatar = async () => {
  console.log('修改头像')
  const res = await uni.chooseImage({
    count: 1,
    sizeType: ['original'],
    sourceType: ['album']
  })
  console.log(res)

  const updateRes = await updateAvatarAPI(res.tempFilePaths[0])
  console.log(updateRes)
}

// 修改性别
const onGenderChange: UniHelper.RadioGroupOnChange = (ev) => {
  profile.value.gender = ev.detail.value as Gender
}
// 修改生日
const onBirthdayChange: UniHelper.DatePickerOnChange = (ev) => {
  profile.value.birthday = ev.detail.value
}
// 修改城市
let fullLocationCode: [string, string, string] = ['', '', '']
const onFullLocationChange: UniHelper.RegionPickerOnChange = (ev) => {
  // 修改前端界面
  profile.value.fullLocation = ev.detail.value.join(' ')
  // 提交后端更新
  fullLocationCode = ev.detail.code!
}

const memberStore = useMemberStore()

// 提交
const onSubmit = async () => {
  const { nickname, gender, birthday, profession, fullLocation } = profile.value
  const res = await putMemberProfileAPI({
    nickname,
    gender,
    birthday,
    profession,
    provinceCode: fullLocationCode[0],
    cityCode: fullLocationCode[1],
    countyCode: fullLocationCode[2]
  })
  console.log('提交结果', res)
  memberStore.profile!.nickname = res.result.nickname
  uni.showToast({ icon: 'success', title: '保存成功' })
  setTimeout(() => {
    uni.navigateBack()
  }, 400)
}
</script>

<template>
  <view class="viewport">
    <!-- 导航栏 -->
    <view class="navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
      <navigator open-type="navigateBack" class="back icon-left" hover-class="none"></navigator>
      <view class="title">个人信息</view>
    </view>
    <!-- 头像 -->
    <view class="avatar">
      <view class="avatar-content" @click="onChangeAvatar">
        <image class="image" :src="profile?.avatar" mode="aspectFill" />
        <text class="text">点击修改头像</text>
      </view>
    </view>
    <!-- 表单 -->
    <view class="form">
      <!-- 表单内容 -->
      <view class="form-content">
        <view class="form-item">
          <text class="label">账号</text>
          <text class="account">{{ profile?.account }}</text>
        </view>
        <view class="form-item">
          <text class="label">昵称</text>
          <input class="input" type="text" placeholder="请填写昵称" v-model="profile.nickname" />
        </view>
        <view class="form-item">
          <text class="label">性别</text>
          <radio-group @change="onGenderChange">
            <label class="radio">
              <radio value="男" color="#27ba9b" :checked="profile?.gender === '男'" />
              男
            </label>
            <label class="radio">
              <radio value="女" color="#27ba9b" :checked="profile?.gender === '女'" />
              女
            </label>
          </radio-group>
        </view>
        <view class="form-item">
          <text class="label">生日</text>
          <picker
            class="picker"
            mode="date"
            start="1900-01-01"
            :end="new Date()"
            :value="profile?.birthday!"
            @change="onBirthdayChange"
          >
            <view v-if="profile?.birthday">{{ profile?.birthday }}</view>
            <view class="placeholder" v-else>请选择日期</view>
          </picker>
        </view>
        <!-- #ifdef H5 -->
        <view class="form-item">
          <text class="label">城市</text>
          <view class="region-select">
            <picker class="picker" :range="provinces" range-key="name" @change="onProvinceChange">
              <view v-if="selectedProvince">{{ selectedProvince }}</view>
              <view class="placeholder" v-else>请选择省份</view>
            </picker>
            <picker
              class="picker"
              :range="cities"
              range-key="name"
              @change="onCityChange"
              :disabled="!selectedProvince"
            >
              <view v-if="selectedCity">{{ selectedCity }}</view>
              <view class="placeholder" v-else>请选择城市</view>
            </picker>
            <picker
              class="picker"
              :range="areas"
              range-key="name"
              @change="onAreaChange"
              :disabled="!selectedCity"
            >
              <view v-if="selectedArea">{{ selectedArea }}</view>
              <view class="placeholder" v-else>请选择区县</view>
            </picker>
          </view>
        </view>
        <!-- #endif -->
        <!-- #ifndef H5 -->
        <view class="form-item">
          <text class="label">城市</text>
          <picker class="picker" mode="region" @change="onFullLocationChange">
            <view v-if="profile?.fullLocation">{{ profile?.fullLocation }}</view>
            <view class="placeholder" v-else>请选择城市</view>
          </picker>
        </view>
        <!-- #endif -->
        <view class="form-item">
          <text class="label">职业</text>
          <input class="input" type="text" placeholder="请填写职业" v-model="profile.profession" />
        </view>
      </view>
      <!-- 提交按钮 -->
      <button class="form-button" @click="onSubmit">保 存</button>
      {{ profile }}
    </view>
  </view>
</template>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/order_bg.png);
  background-size: auto 420rpx;
  background-repeat: no-repeat;
}

// 导航栏
.navbar {
  position: relative;

  .title {
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-weight: 500;
    color: #fff;
  }

  .back {
    position: absolute;
    height: 40px;
    width: 40px;
    left: 0;
    font-size: 20px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

// 头像
.avatar {
  text-align: center;
  width: 100%;
  height: 260rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;

  .image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 50%;
    background-color: #eee;
  }

  .text {
    display: block;
    padding-top: 20rpx;
    line-height: 1;
    font-size: 26rpx;
    color: #fff;
  }
}

// 表单
.form {
  background-color: #f4f4f4;

  &-content {
    margin: 20rpx 20rpx 0;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  &-item {
    display: flex;
    height: 96rpx;
    line-height: 46rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;

    &:last-child {
      border: none;
    }

    .label {
      width: 180rpx;
      color: #333;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .radio {
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;
    }
    .placeholder {
      color: #808080;
    }
  }

  &-button {
    height: 80rpx;
    text-align: center;
    line-height: 80rpx;
    margin: 30rpx 20rpx;
    color: #fff;
    border-radius: 80rpx;
    font-size: 30rpx;
    background-color: #27ba9b;
  }
}

.region-select {
  flex: 1;
  display: flex;
  gap: 10rpx;

  .picker {
    flex: 1;

    view {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
</style>
